<template>
  <!-- 弹窗部分 -->
  <uni-popup ref="scanPopup" type="center" v-if="showScanModal">
    <view class="modal-overlay" @click.stop="closeScanModal"></view>
    <view class="modal-container">
      <view class="close-btn" @click="closeScanModal">
        <uni-icons type="closeempty" size="24" color="#999"></uni-icons>
      </view>
      
		<view class="modal-content">
			<text class="title">扫描结果</text>
			<text>进仓单号:</text>
			<input 
				v-model="scanModalData.billNo" 
				placeholder="已自动填充单号" 
				disabled="false"
				class="input"
			/>
			<text>物料名称:</text>
			<input 
				v-model="scanModalData.goodsName" 
				placeholder="物料名称" 
				disabled="false"
				class="input"
			/>
			<text>图号版本-规格:</text>
			<textarea 
				v-model="scanModalData.designNumberVerSpec"
				placeholder="图号版本-规格"
				disabled="false"
				auto-height
				class="input"
			></textarea>
			<text>入仓数量:</text>
			<input
				class="input"
				v-model="scanModalQty"
				type="number"
				placeholder="请输入单据数量"
			/>
		</view>

		<view class="modal-footer">
			<button class=" btn cancel" @click="closeScanModal">取消</button>
			<button class=" btn confirm" @click="confirmScanModal">确认</button>
		</view>
    </view>
  </uni-popup>

	<view class="card">
		<view class="card-item">
			<text class="label">进仓单号：</text>
			<input 
				class="value"
				v-model="billNo"
				disabled="false"
			/>
		</view>
		<view class="card-item">
			<text class="label">单据状态：</text>
			<input 
				class="value"
				v-model="billStatus"
				disabled="false"
			/>
		</view>
		<view class="card-item">
			<text class="label">收货仓库：</text>
			<picker
				class="value"
				:range="options" 
			    :range-key="'label'" 
			    @change="handlePickerChange"
			>
				<view class="picker-box">
					{{ selectedLabel || '请选择' }}
			    </view>
			</picker>
		</view>
		<view class="card-item">
			<text class="label">进仓日期：</text>
			<picker class="value" mode="date" @change="onDateChange" :value="dateValue">
				<view class="date-picker">{{ formattedDate }}</view>
			</picker>
		</view>
		<view class="card-item">
			<text class="label">备注：</text>
			<textarea 
				class="value"
				v-model="remark"
				placeholder="可输入备注"
				auto-height
			/>
		</view>
		<view class="card-item">
			<text class="label">制单：</text>
			<input
				class="value"
				v-model="createBy"
				disabled="false"
			/>
		</view>
		<view class="card-item">
			<text class="label">制单时间：</text>
			<input
				class="value"
				v-model="createDate"
				disabled="false"
			/>
		</view>
		<view class="card-item">
			<text class="label">审核：</text>
			<input
				class="value"
				v-model="checkBy"
				disabled="false"
			/>
		</view>
		<view class="card-item">
			<text class="label">审核时间：</text>
			<input
				class="value"
				v-model="checkDate"
				disabled="false"
			/>
		</view>
	</view>
	<uni-popup ref="waPopup" type="center" v-if="showWAModal">
		<view class="modal-overlay" @click.stop="closeWAModal"></view>
		<view class="modal-container">
			<view class="close-btn" @click="closeWAModal">
				<uni-icons type="closeempty" size="24" color="#999"></uni-icons>
			</view>
			<view v-for="(la, index) in ls" :key="la.id">
				<view class="waDataWindow">
					<text class="waText">仓库{{ index + 1 }}:</text>
					<input
						v-model="la.workingAreaName" 
						placeholder="仓库" 
						disabled="false"
						class="waInput"
					/>
				</view>
				<view class="waDataWindow">
					<text class="waText">库位编号:</text>
					<input
						v-model="la.locationCode" 
						placeholder="库位编号" 
						class="waInput"
					/>
				</view>
				<view class="waDataWindow">
					<text class="waText">库位名称:</text>
					<input
						v-model="la.locationName"
						class="waInput"
					/>
				</view>
				<view class="waDataWindow">
					<text class="waText">现存数量：</text>
					<input
						v-model="la.onHandQty"
						placeholder="请输入现存数量" 
						class="waInput"
					/>
				</view>
			</view>
			<view class="modal-footer">
				<button class="btn cancel" @click="closeWAModal">取消</button>
				<button class="btn confirm" @click="confirmWAModal">确认</button>
			</view>
		</view>
	</uni-popup>
	<view class="card" v-if="qty">
		<view class="card-item">
			<view class="row-block">
				<image
					v-if="imageUrl"
					:src= "imageUrl"
					mode="aspectFill"
					lazy-load
					class="preview-image"
					@error="handleImageError"
				/>
			</view>
			<view class="row-block">
				<button 
					v-if="pdfUrl"
					class="pdf-btn"
					@tap.stop="handleDownloadPdf"
				>
					查看 PDF 图
				</button>
			</view>
		</view>
		<view class="card-item">
			<text class="label">可进仓数量：</text>
			<input 
				class="value"
				v-model="qty"
				placeholder="请输入可进仓数量"
				disabled="false"
			/>
		</view>
		<view class="card-item">
			<text class="label">物料名称：</text>
			<input 
				class="value"
				v-model="goodsName"
				placeholder="请输入物料名称"
				disabled="false"
			/>
		</view>
		<view class="card-item">
			<text class="label">库存数量a：</text>
			<input 
				class="value"
				v-model="qty"
				placeholder="请输入库存数量"
			/>
			<text class="value2">{{ unitName }}</text>
		</view>
		<view class="card-item">
			<text class="label">车间任务单号：</text>
			<input 
				class="value"
				v-model="productBillNo"
				placeholder="请输入车间任务单号"
				disabled="false"
			/>
		</view>
		<view class="card-item">
			<text class="label">物料编号：</text>
			<input 
				class="value"
				v-model="goodsCode"
				placeholder="请输入物料编号"
				disabled="false"
			/>
		</view>
		
		<view class="card-item">
			<text class="label">库位：</text>
			<view class="location-wrapper">
			<view class="location-box">
			<view v-for="la in ls" :key="la.id" class="location-box">
				<text class="location-line">{{ la.workingAreaName }} {{ la.workingCenterCode }} {{la.locationName}}</text><div></div>
				<text class="location-line">数量：{{ la.onHandQty }}</text>
			</view>
			</view>
			</view>
			<button class="edit-btn" @tap="handleUpdateWA">修改库位</button>
		</view>
		<view class="card-item">
			<text class="label">完工工序：</text>
			<input 
				class="value"
				v-model="wpName"
				placeholder="请输入完工工序"
				disabled="false"
			/>
		</view>
		<view class="card-item">
			<text class="label">图号版本-规格：</text>
			<textarea 
				class="value"
				v-model="designNumberVerSpec"
				placeholder="请输入图号版本-规格"
				disabled="false"
				auto-height
			/>
		</view>
	</view>
	<button class="addDetail" @tap="startScan">扫码获取明细</button>
	<button class="save-btn" @tap="handleSave">保存</button>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, vShow, reactive} from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import { formatTime } from '@/pages/utils/formatTime'
import { LAN_URL } from '@/pages/config/global'
import { DOWNLOAD_BASE } from '@/pages/config/global'

const ADD_URL = '/produceDetail/addDetail'
const FETCH_URL = '/produceDetail/fetchDetail'
const AREA_URL = '/produceDetail/getAreaName'
const OPTIONS_URL = '/produceRepair/waOptions'
const USER_OPRIONS_URL = '/produceRepair/userOptions'
const GETNUM_URL = '/produceDetail/getBillNum'
const FETCH_DETAIL_URL = '/productBillDetail/fetchDetail'
const ADD_DETAIL_URL = '/productBillDetail/addDetail'
const UPDATE_DETAIL_URL = '/productBillDetail/updateDetail'
const STATUS_URL = '/productBillDetail/getStatus'
const GOODS_POWER_URL = '/productBillDetail/getGoodsPower'
const FILES_URL = '/productBillDetail/getFilesUrl'
const WP_CN_URL = '/productBillDetail/getWpCn'
const UNITS_CN_URL = '/productBillDetail/getUnitCn'
const CHECK_WP_URL = '/productBillDetail/checkWpLast'
const LOCATION_URL = '/productBillDetail/getLocation'
const UPDATE_WA_URL = '/productBillDetail/updateLocation'
const GET_GOODS_URL = '/productBillDetail/getGoods'

const billNo = ref(null)
const billStatus = ref('未审核')
const billName = ref('工序进仓单')
const workingAreaCode = ref(null)
const createBy = ref(null)
const createDate = ref(null)
const checkBy = ref(null)
const checkDate = ref(null)
const remark = ref(null)
const qty = ref(null)
const goodsName = ref(null)
const unitCode = ref(null)
const unitName = ref(null)
const productBillNo = ref(null)
const goodsCode = ref(null)
const waLocationCode = ref(null)
const wpCode = ref(null)
const wpName = ref(null)
const designNumberVerSpec = ref(null)
const imageUrl = ref(null)
const pdfUrl = ref(null)

const dateValue = ref<string>(formatTimePicker(new Date()))

const detailData = ref<Array<{
	planCode: string,
	billNo: string,
	checked: number,
	goodsCode: string,
	goodsName: string,
	designNumberVerSpec: string,
	unitCode: string,
	workingAreaCode: string,
	workingCenterCode: string,
	wpNo: number,
	wpNoLast: number,
	wpCode: string,
	planQty: number,
	id: number,
	workgroupCodestring: string,
	wpId: number,
	inProcessQty: number,
	inQty: number,
	repairQty: number,
	completeQty: number,
	goodsName2string: string,
	designNumberVerSpec2string: string,
	clientNamestring: string,
	clientGoodsCodestring: string,
	orderNostring: string,
	clientOrderNostring: string,
	notInQty: number,
	parmMustCompleteWork: string,
	combinationBillNo: string,
	combinationWpId: number,
	remark: string,
}>>([])

const showScanModal = ref(false)
const scanPopup = ref()
const scanModalData = ref<any>({})
const scanModalQty = ref('')

const options = ref<OptionItem[]>([])
const selectedValue = ref('')
const selectedLabel = ref('') 

const showWAModal = ref(false)
const waPopup = ref()

interface OptionItem {
	label: string;
	value: string;
}

const ls = ref<LocationStock[]>([])
interface LocationStock {
	id: number;
	workingAreaCode: string;
	locationCode: string;
	goodsCode: string;
	batchNo: string | null;
	onHandQty: number | null;
	workingCenterCode: string;
	locationName: string;
	workingAreaName: string;
}
const df = ref<DetailForm[]>([])
interface DetailForm {
	id: number,
	billNo: string,
	productBillNo: string,
	wpID: 1,
	goodsCode: string,
	
	billStatus: string,
	billType: string,
	workingAreaCode: string,
	inOutDate: string,
	remark: string,
	createBy: string,
	createDate: string,
	goodsName: string,
	unitCode: string,
	waLocationCode: string,
	wpCode: string,
	designNumberVerSpec: string,
	qty: number
}

onLoad(() => {
	detailData.value = null
	loadProduct();
})

onMounted(() => {
	fetchOptions();
})

/* 加载单号信息 */
const loadProduct = () => {
	const product = uni.getStorageSync('product');
	const user = uni.getStorageSync('user');
	const now = new Date();
	console.log(product)
	if (product) {
		billNo.value = product.billNo
		try {
			uni.request({
				url: `${LAN_URL}${FETCH_URL}`,
				method: 'POST',
				data: { billNo: billNo.value },
				success: (res) => {
					const resData = res.data
					console.log(resData)
					billStatus.value = resData.billStatus || null
					selectedValue.value = resData.workingAreaCode || null
					uni.request({
						url: `${LAN_URL}${AREA_URL}`,
						method: 'POST',
						data: { workingAreaCode: selectedValue.value },
						success: (res) => {
							 const resData2 = res.data
							 selectedLabel.value = resData2.workingAreaName
						}
					})
					workingAreaCode.value = selectedValue.value
					remark.value = resData.remark || null
					createBy.value = resData.createBy || null
					createDate.value = resData.createDate || null
					getGoods(billNo.value);
				},fail() {
					uni.showToast({ title: '没有查询到数据', icon: 'error' })
					return;
				}
			})
		}catch {
			uni.showToast({ title: '网络错误', icon: 'error' })
		}
	}else {
		billStatus.value = '未审核'
		createDate.value = formatTime(now)
		createBy.value = user.name
	}
}
/* 显示日期 yyyy-MM-dd */
const formattedDate = computed(() => {
	const date = new Date(dateValue.value)
	return formatDisplay(date)
})
/* 更改日期同步到dateValue值 */
const onDateChange = (e: any) => {
    dateValue.value = e.detail.value;
}

/* 扫码模块 - 检查状态 */
const startScan = async () => {
	if(billNo.value != null) {
		try {
			uni.request({
				url: `${LAN_URL}${STATUS_URL}`,
				method: 'POST',
				data: { billNo: billNo.value },
				success(res) {
					const resData = res.data;
					console.log(res)
					if(resData == "未审核"){
						handleScan();
					}else {
						uni.showToast({
							title: '单据已审核，请刷新',
							icon:'none'
						})
					}
				},fail() {
					uni.showToast({
						title: '网络错误',
						icon:'none'
					})
				}
			})
		}catch {
			uni.showToast({
				title: '网络错误',
				icon:'none'
			})
		}		
	}else {
		handleScan()
	}
}
/* 扫码模块 - 检查工作区域存在后执行扫码 */
const handleScan = () => {
	let workStatus = ref(true);
	if(workingAreaCode.value == null) {
		uni.showToast({
			title: '请先选择工作区域',
			icon: 'none'
		})
		workStatus.value = false;
	}
	if(!workStatus.value){	
		workStatus.value = false;
		return;
	}
	try {
		uni.scanCode({
			scanType: ['qrCode', 'barCode'],
			onlyFromCamera: true,
			success: (result) => {
				handleScanResult(result)
			},
			fail: (err) => {
				handleScanError(err)
			}
		})
	} catch (error) {
		handleScanError(error)
	}
}
/* 扫码模块 - 查询扫码结果 */
const handleScanResult = (result: UniApp.ScanCodeSuccessRes) => {
	//console.log("resule:", result.result)
	if (result.scanType === 'EAN_13') {
		console.log("1")
	}
	uni.request({
		url: `${LAN_URL}${FETCH_DETAIL_URL}`, // 后端接口
		method: 'POST',
		data: {
			data: result.result.trim(),
		},
		success: (res) => {
			if (res.statusCode == 200 && res.data != ''){
				console.log(res.data) //有数据了已经
				scanModalData.value = res.data[0] || res.data
				scanModalQty.value = scanModalData.value.notInQty?.toString() || '1'
				console.log(scanModalData)
				const goodCode = ref(null)
				goodCode.value = scanModalData.value.goodsCode
				
				const user = uni.getStorageSync('user')
				const userID = ref<string | null>(null)
				userID.value = user.id
				
				uni.request({
					url: `${LAN_URL}${GOODS_POWER_URL}`,
					method: 'POST',
					data: { goodsCode: goodCode.value, userID: userID.value},
					success(res) {
						if(res.data) {
							/* 获取文件地址 */
							uni.request({
								url: `${LAN_URL}${FILES_URL}`,
								method: 'POST',
								data: { goodsCode: goodsCode.value },
								success(res) {
									const data = res.data
									imageUrl.value = data.imageUrl ? `${DOWNLOAD_BASE}${res.data.imageUrl}` : undefined
									pdfUrl.value = data.pdfUrl ? `${DOWNLOAD_BASE}${res.data.pdfUrl}` : undefined
								}
							})
							getWpCn();
							getUnitCn();
							getLocation();
							showScanModal.value = true
							scanPopup.value.open();
						}else {
							uni.showToast({
								title: '未拥有对应物料权限',
								icon: 'none'
							})
						}						
					},
					fail() {
						uni.showToast({
							title: '未找到对应数据',
							icon: 'none'
						})
					}
				})
			}else {
				uni.showToast({
					title: '未找到对应数据',
					icon: 'none'
				})
			}
		},
		fail() {
			uni.showToast({
				title: '网络异常',
				icon: 'none'
			})
		}
	})
}
/* 确认扫码后弹窗结果 */
const confirmScanModal = () => {
  if (!scanModalQty.value) {
    uni.showToast({ title: '请输入数量', icon: 'none' })
	return;
  }else {
		productBillNo.value = scanModalData.value.billNo
		goodsName.value = scanModalData.value.goodsName
		unitCode.value = scanModalData.value.unitCode
		goodsCode.value = scanModalData.value.goodsCode
		waLocationCode.value = scanModalData.value.waLocationCode
		wpCode.value = scanModalData.value.wpCode
		designNumberVerSpec.value = scanModalData.value.designNumberVerSpec
		qty.value = scanModalQty.value
		
		detailData.value = null;
		showScanModal.value = false
		scanPopup.value.close();
		closeScanModal();
  }
}
/* 检验扫码结果重复性 */
const handleModalConfirm = (data: any) => {
	// 检查是否已存在相同物料
	const existsIndex = detailData.findIndex(
		item => item.goodsCode === data.goodsCode
	)
	console.log(existsIndex)
	if (existsIndex >= 0) {
		// 如果已存在，更新数量
		detailData[existsIndex].qty = data.qty
	} else {
		// 如果不存在，添加新记录
		detailData.push({
			goodsCode: data.goodsCode,
			goodsName: data.goodsName,
			qty: data.qty,
			unitCode: data.unitCode,
			productBillNo: data.productBillNo,
			waLocationCode: data.waLocationCode,
			wpCode: data.wpCode,
			designNumberVerSpec: data.designNumberVerSpec
		})
	}
	closeScanModal()
}

/* 关闭弹窗操作 */
const closeScanModal = () => {
	ls.value = null;
	showWAModal.value = false;
	detailData.value = null;
	showScanModal.value = false;
	scanPopup.value.close();
}

/* 工序转中文 */
const getWpCn = () => {
	uni.request({
		url: `${LAN_URL}${WP_CN_URL}`,
		method: 'POST',
		data: { wpCode: scanModalData.value.wpCode },
		success(res) {
			const data = res.data
			wpName.value = data.wpName ? data.wpName : null
		}
	})
}

/* 单位转中文 */
const getUnitCn = () => {
	uni.request({
		url: `${LAN_URL}${UNITS_CN_URL}`,
		method: 'POST',
		data: { unitCode: scanModalData.value.unitCode },
		success(res) {
			const data = res.data
			unitName.value = data.unit ? data.unit : undefined
		}
	})
}

/* 获取库位信息 */
const getLocation = () => {
	uni.request({
		url: `${LAN_URL}${LOCATION_URL}`,
		method: 'POST',
		data: { goodsCode: goodsCode.value },
		success(res) {
			const data = res.data
			ls.value = data.map((item: { id: number; workingAreaCode: string; locationCode: string; goodsCode: string; batchNo: string | null; onHandQty: number | null; workingCenterCode: string; locationName: string; workingAreaName: string }) => ({
				id: item.id,
				workingAreaCode: item.workingAreaCode,
				locationCode: item.locationCode,
				goodsCode: item.goodsCode,
				batchNo: item.batchNo,
				onHandQty: item.onHandQty,
				workingCenterCode: item.workingCenterCode,
				locationName: item.locationName,
				workingAreaName: item.workingAreaName
			}))
			console.log(ls)
		}
	})
}
/* 更新库位信息 */
const handleUpdateWA = () => {
	if(ls == null){
		console.log("1")
		getLocation();
	}
	showWAModal.value = true
	waPopup.value.open();
}
/* 关闭库位弹窗 */
const closeWAModal = () => {
	showWAModal.value = false
	waPopup.value.close()
}
/* 确认库位弹窗信息 */
const confirmWAModal = async () => {
	console.log(ls.value.onHandQty)
	try {
		const batchSize = 2;
		const totalBatches = Math.ceil(ls.value.length / batchSize);
		for (let i = 0; i < totalBatches; i++){
			const start = i * batchSize;
			const end = Math.min(start + batchSize, ls.value.length);
			const batchData = ls.value.slice(start, end);
			const response = await uni.request({
				url: `${LAN_URL}${UPDATE_WA_URL}`, // 替换为你的后端API地址
				method: 'POST',
				data: batchData,
			})
			console.log(response)
			if(response.statusCode == 200) {
				console.log(`第${i + 1}批更新成功`)
			}else {
				console.log(`第${i + 1}批更新失败`)
			}
			showWAModal.value = false
			waPopup.value.close();
			closeWAModal();
		}
	}catch(error) {
		uni.showToast({
			title: '读取库位异常：', error,
			icon: 'none'
		})
		console.error('错误:', error);
	}
}
/* 转换字段 */
const convertToLocationUpdate = (stock: LocationStock): LocationUpdateStock => {
	return {
		id: stock.id,
		workingAreaCode: stock.workingAreaCode,
		locationCode: stock.locationCode,
		goodsCode: stock.goodsCode,
		batchNo: stock.batchNo,
		onHandQty: stock.onHandQty,
	}
}

/* 获取仓库选项 */
const fetchOptions = async () => {
	try {
		const user = uni.getStorageSync('user')
		const userID = ref<string | null>(null)
		userID.value = user.id
		const res = await uni.request({
			url: `${LAN_URL}${USER_OPRIONS_URL}`,
			method: 'POST',
			header: {
				'Content-Type': 'application/json',			
			},
			data: {
				property: "仓库",
				userID: userID.value
			}
		})
		if (res.statusCode === 200) {
		    const data = res.data as any[]
		    options.value = data.map(item => ({
		        label: item.label,
		        value: item.value
		    }))
		} else {
		    console.error('请求失败', res)
		}
	}catch {
		uni.showToast({ title: '获取数据失败', icon: 'none' })
	}
}

/* 变更仓库信息 */
const handlePickerChange = (e: any) => {
	const index = e.detail.value
	selectedValue.value = options.value[index].value
	selectedLabel.value = options.value[index].label
	workingAreaCode.value = selectedValue.value
	//console.log('选择：', selectedLabel.value, selectedValue.value)
}

/* 详细单保存操作 - 检查 */
const handleSave = () => {
	/* 检查审核状态 */
	if (billStatus.value != '未审核'){
		uni.showToast({
			title: '该单已通过审核',
			icon: 'none'
		})
		return;
	}
	/* 检查仓库信息 */
	if (workingAreaCode.value == null){
		uni.showToast({
			title: '请选择工作区域',
			icon: 'none'
		})
		return;
	}
	/* 检查进仓日期是否为空 */
	if (dateValue == null){
		uni.showToast({
			title: '请选择进仓日期',
			icon: 'none'
		})
		return;
	}
	
	/* 日期与系统日期不符，需提醒 */
	const selectDate = new Date(dateValue.value)
	const currentDate = new Date()
	selectDate.setHours(0,0,0,0)
	currentDate.setHours(0,0,0,0)
	if (selectDate.getTime() != currentDate.getTime()){
		uni.showModal({
			title: '提示',
			content: '选择的日期不是今天，是否继续保存？',
			success: (res) => {
				if (res.confirm) {
					checkWpNo();
				}
			}
		})
	}else {
		checkWpNo();
	}
}
/* 检验工序顺序 */
const checkWpNo = () => {
	uni.request({
		url: `${LAN_URL}${CHECK_WP_URL}`,
		method: 'POST',
		data: { billNo: productBillNo.value },
		success(res) {
			if(res.statusCode != 200 || !res.data){
				uni.showToast({
					title: '不是最后一个工序，不可进仓。',
					icon: 'none'
				})
				return;
			}
			getBillNo();
		},fail() {
			uni.showToast({
				title: '网络错误',
				icon: 'none'
			})
			return;
		}
	})
}
/* 当单号为空时获取单号 */
const getBillNo = () => {
	if(billNo.value == null){
		if(goodsName.value == null) {
			uni.showToast({
				title: '未添加明细',
				icon: 'none'
			})
			return;
		}
		uni.request({
			url: `${LAN_URL}${GETNUM_URL}`,
			method: 'POST',
			data: {
				billName: billName.value
			},
			success: (res) => {
				if (res.data && res.data != null && res.data != "取单号时出错") {
					billNo.value = res.data;
					saveDetail();
				} else {
					uni.showToast({
						title: '保存失败，请重新保存',
						icon: 'none'
					});
					return;
				}
			}, fail() {
				uni.showToast({
					title: '保存失败，请重新保存',
					icon: 'none'
				});
				return;
			}
		})
	}else {
		updateDetail();
	}
}
/* 详细单保存操作 - 提交 */
const saveDetail = async () => {
	if(scanModalData) {
		const { data } = await uni.request({
			url: `${LAN_URL}${ADD_DETAIL_URL}`,
			method: 'POST',
			data: {
				id: 1,
				billNo: billNo.value,
				productBillNo: productBillNo.value,
				wpID: 1,
				goodsCode: goodsCode.value,
				
				billStatus: billStatus.value,
				billType: billName.value,
				workingAreaCode: workingAreaCode.value,
				inOutDate: new Date(dateValue.value),
				remark: remark.value,
				createBy: createBy.value,
				createDate: createDate.value,
				goodsName: goodsName.value,
				unitCode: unitCode.value,
				waLocationCode: waLocationCode.value,
				wpCode: wpCode.value,
				designNumberVerSpec: designNumberVerSpec.value,
				qty: qty.value
			}
		})
		try {
			const { data } = await uni.request({
				url: `${LAN_URL}${ADD_URL}`,
				method: 'POST',
				data: { 
					billNo: billNo.value,
					billStatus: billStatus.value,
					billType: billName.value,
					workingAreaCode: workingAreaCode.value,
					inOutDate: new Date(dateValue.value),
					remark: remark.value,
					createBy: createBy.value,
					createDate: createDate.value
				}
			})	
			uni.showToast({ title: '保存成功' })
		} catch (error) {
			uni.showToast({ title: '添加失败', icon: 'error' })
		}
	}else {
		uni.showToast({ title: '未添加明细', icon: 'error' })
	}
}
/* 详细单保存操作 - 更新 */
const updateDetail = async () => {
	if(scanModalData) {
		const { data } = await uni.request({
			url: `${LAN_URL}${UPDATE_DETAIL_URL}`,
			method: 'POST',
			data: {
				id: 1,
				billNo: billNo.value,
				productBillNo: productBillNo.value,
				wpID: 1,
				goodsCode: goodsCode.value,
				
				billStatus: billStatus.value,
				billType: billName.value,
				workingAreaCode: workingAreaCode.value,
				inOutDate: new Date(dateValue.value),
				remark: remark.value,
				createBy: createBy.value,
				createDate: createDate.value,
				goodsName: goodsName.value,
				unitCode: unitCode.value,
				waLocationCode: waLocationCode.value,
				wpCode: wpCode.value,
				designNumberVerSpec: designNumberVerSpec.value,
				qty: qty.value
			}
		})
		/* //以下需要修复
		try {
			const { data } = await uni.request({
				url: `${LAN_URL}${ADD_URL}`,
				method: 'POST',
				data: {
					billNo: billNo.value,
					billStatus: billStatus.value,
					billType: billName.value,
					workingAreaCode: workingAreaCode.value,
					inOutDate: new Date(dateValue.value),
					remark: remark.value,
					createBy: createBy.value,
					createDate: createDate.value
				}
			})	
			uni.showToast({ title: '保存成功' })
			
		} catch (error) {
			uni.showToast({ title: '添加失败', icon: 'error' })
		} */
	}else {
		uni.showToast({ title: '未添加明细', icon: 'error' })
	}
}
/* 获取明细 */
const getGoods = (billNo: string) => {
	try {
		uni.request({
			url: `${LAN_URL}${GET_GOODS_URL}`,
			method: 'POST',
			data: {billNo: billNo},
			success() {
				
			}
		})
	}catch {
		uni.showToast({ title: '网络错误', icon: 'error' })
	}
}

/* 获取文件名 */
const getFileNameFromUrl = (url: string) => {
	// 处理带参数的URL
	const cleanUrl = url.split('?')[0]
	// 获取最后一个斜杠后的内容
	const parts = cleanUrl.split('/')
	return parts[parts.length - 1] || `document_${Date.now()}.pdf` // 默认文件名
}
const handleImageError = () => {
	imageUrl.value = '/static/images/placeholder.png'
}
/* 下载PDF */
const handleDownloadPdf = async () => {
	if (!pdfUrl) return;

	try {
		const fileName = getFileNameFromUrl(pdfUrl.value)
		const saveDir = '_doc/uniapp_save/'
		
		const { tempFilePath } = await uni.downloadFile({
			url: pdfUrl.value
		})
		let savedPath = '';
		
		// #ifdef MP-WEIXIN
		savedPath = `${uni.env.USER_DATA_PATH}/${Date.now()}.pdf`
		// #endif
	
		// #ifdef APP-PLUS
		savedPath = `${plus.io.convertLocalFileSystemURL(saveDir)}${fileName}`
		// #endif
		uni.openDocument({
			filePath: savedPath,
			success: () => {
			    console.log("PDF文件已成功不下载打开");
			},
			fail() {
				uni.saveFile({
					tempFilePath, filePath: savedPath, success(res) {
						console.log("res:" + res.savedFilePath)
						plus.io.resolveLocalFileSystemURL(res.savedFilePath,
							(entry) => {
								console.log("实际存储路径:", "fullPath" + entry.fullPath);
								console.log("savedPath:",savedPath)
								//重命名文件
								plus.io.resolveLocalFileSystemURL(saveDir, (dirEntry) => {
								    entry.moveTo(dirEntry, fileName, (newEntry) => {
										console.log("文件已重命名:", newEntry.fullPath);
									}, (err) => {
										console.error("文件重命名失败:", err);
									});
								});
							}, 
							(err) => {
								console.log("找不到文件:", err);
							}
						);
						uni.openDocument({
							filePath: res.savedFilePath,
							success: () => {
								console.log("PDF文件已成功打开");
							},
							fail: (err) => {
								console.error("PDF打开失败:", err);
							}
						});
					},fail(err) {
						uni.showToast({ title: '文件不存在', icon: 'error' })
						console.log(err)
					}
				})
			}
		})
	} catch (error) {
		uni.showToast({ title: '文件打开失败', icon: 'none' })
	}
}

/* 更改日期格式 YYYY-MM-DD */
function formatTimePicker(date: Date): string {
	const pad = (n: number) => n.toString().padStart(2, '0')
	const year = date.getFullYear()
	const month = pad(date.getMonth() + 1)
	const day = pad(date.getDate())
	return `${year}-${month}-${day}`
}
/* 更改日期为中文格式 YYYY年MM月DD日 */
function formatDisplay(date: Date): string {
	const pad = (n: number) => n.toString().padStart(2, '0')	
	return `${date.getFullYear()}年${pad(date.getMonth() + 1)}月${pad(date.getDate())}日`
}
/* 扫码失败提示 */
function handleScanError(err: any) {
	uni.showToast({
		title:'扫码失败',
		icon:'none'
	})
	throw new Error('Function not implemented.');
}



</script>

<style scoped>
.card {
	background-color: #fff;
	padding: 24rpx;
	margin: 24rpx;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
}
.card-item {
	display: flex;
	flex-wrap: wrap;
	margin-bottom: 16rpx;
}
.row-block {
	  width: 100%;
	}
.preview-image {
	 width: 100%;
	 height: 300rpx;
	border-radius: 8rpx;
	margin-top: 20rpx;
	background: #f0f0f0;
}
.pdf-btn {
  width: 100%;
    margin-top: 20rpx;
	background: #4CAF50;
	color: white;
    border-radius: 8rpx;
    padding: 12rpx 0;
    font-size: 28rpx;
    border: none;
    box-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1);
}

.label {
	width: 200rpx;
	color: #888;
	font-weight: bold;
}
.value {
	flex: 1;
	color: #333;
	border: 1px solid #ccc;
	border-radius: 8rpx;
    padding: 8rpx;
    background-color: #f9f9f9;
}
.value2 {
	flex: 1;
	color: #333;
	border: none;
	border-radius: 8rpx;
	padding: 8rpx;
	background-color: #f9f9f9;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.modal-container {
	position: relative;
	z-index: 1001;
	background: #fff;
	border-radius: 16rpx;
	padding: 40rpx 30rpx;
	max-width: 80vw;
	margin: 0 auto;
	box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
}

.close-btn {
	position: absolute;
	left: 20rpx;
	top: 20rpx;
}

.title {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 30rpx;
	display: block;
}

.input {
	margin-top: 10rpx;
	width: 100%;
	height: 80rpx;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
	padding: 0 20rpx;
	margin-bottom: 30rpx;
}

.modal-footer {
	display: flex;
	justify-content: space-between;
	margin-top: 40rpx;
}

.btn {
	flex: 1;
	height: 80rpx;
	line-height: 80rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
}

.cancel {
	background: #f0f0f0;
	color: #333;
	margin-right: 20rpx;
}

.confirm {
	background: #007aff;
	color: white;
}


.location-wrapper {
  position: relative;
  flex: 1;
  display: flex;
  align-items: flex-start;
  margin-top: -15rpx;
  margin-left: -80rpx;
}
.location-box {
  flex: 1;
  background: none;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx;
  box-sizing: border-box;
}
.location-line {
  font-size: 28rpx;
  color: #000000;
  line-height: 40rpx;
}
.edit-btn {
  margin-left: 10rpx;
  background-color: #ddd;
  color: black;
  font-size: 26rpx;
  padding: 6rpx 20rpx;
  height: 48rpx;
  line-height: 48rpx;
  border: none;
  border-radius: 8rpx;
  align-self: flex-start;
}
.waText {
	width: 160rpx;
	white-space: nowrap;
}
.waDataWindow {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;
}
.waInput {
	flex: none;
	margin-left: 30rpx;
	width: 50%;
	border: 1px solid #ddd;
	border-radius: 8rpx;
}
</style>